
class ScreenStatus {
  /** @type string */
  sid = null;
  /** @type string */
  name = null;
  /** @type string */
  series = null;
  /** @type string */
  scene = null;
  /** @type string */
  scope = null;
  /** @type boolean */
  connect = null;
  /** @type any */
  data = null;
  /** @type Date */
  instant = null;

  /**
   * @returns {ScreenStatus}
   */
  clone = function () {
    return cloneOne.call(this, this); // 第一个 this 无效, 第二个 this = cloneOne 参数 raw
  };

  /**
   * @returns {string}
   */
  screenName = function (textLen = 10, sidLen = 18) {
    if (this.name) {
      if (this.name.length > textLen) {
        return this.name.substring(0, textLen) + " ...";
      } else {
        return this.name;
      }
    }
    return this.sid.substring(0, sidLen) + " ...";
  };

  sceneName = function () {
    if (this.scene || this.series) {
      return `${this.series}/${this.scene}`;
    }
    return null;
  };
};

// 暂存数据
/** @type {ScreenStatus[]} */
let currentScreenStatus = [];

/**
 * @param {object} raw
 * @returns {ScreenStatus}
 */
function cloneOne(raw) {
  let s = new ScreenStatus(); // Object.assign(s, raw)
  s.sid = raw.sid;
  s.name = raw.name;
  s.series = raw.series;
  s.scene = raw.scene;
  s.connect = raw.connect;
  s.data = raw.data;
  s.instant = raw.instant;
  return s;
}

/**
 * @returns {ScreenStatus[]}
 */
function getAll() {
  return currentScreenStatus.map(s => s.clone());
}

function refreshAll(array) {
  currentScreenStatus = array.map(item => cloneOne(item));
}

/**
 * @param {ScreenStatus} s 
 */
function updateOne(s) {
  let index = -1;
  for (let i = 0; i < currentScreenStatus.length; i++) {
    if (currentScreenStatus[i].sid === s.sid) {
      index = i;
      break;
    }
  }
  if (index === -1) {
    return;
  }
  currentScreenStatus[index] = cloneOne(s);
}

/**
 * @param {ScreenStatus} s 
 */
function insertOne(s) {
  currentScreenStatus.push(s);
}

/**
 * @param {string} sid
 */
function deleteOne(sid) {
  currentScreenStatus = currentScreenStatus.filter((s) => s.sid !== sid);
}

function getOne(sid) {
  let s = currentScreenStatus.filter(s => s.sid === sid);
  return (s.length) ? s[0].clone() : null;
}

export default {ScreenStatus, cloneOne, getOne, getAll, insertOne, deleteOne, updateOne, refreshAll};
